<template>
  <div class="app-container">
    <el-row style="margin-bottom:10px;">
      <el-input placeholder="猪肉ID" style="margin-left:5px;float:left;width:100px;" />
      <el-input placeholder="部位名称" style="margin-left:5px;float:left;width:150px;" />
      <el-input placeholder="重量" style="margin-left:5px;float:left;width:150px;" />
      <el-button type="primary" icon="el-icon-search" style="margin-left:5px;float:left;width:100px;">搜索</el-button>
      <el-button
        type="primary"
        style="float:right"
        @click="newRow"
      >购买猪肉</el-button>
    </el-row>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="45"
      />
      <el-table-column align="center" label="ID" width="45">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="部位名称" show-overflow-tooltip align="center">
        <template slot-scope="scope">
          {{ scope.row.part_name }}
        </template>
      </el-table-column>
      <el-table-column label="重量" show-overflow-tooltip align="center" width="70">
        <template slot-scope="scope">
          {{ scope.row.weight }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="cut_date" label="分割时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.cut_date }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="280">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="showsplit(scope.row)">分块</el-button>
          <el-button type="info" size="mini" @click="editRow(scope.row)">编辑</el-button>
          <el-button :loading="buttonloading" size="mini" type="danger" @click="deleteRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="rowdata" title="猪肉分块" :visible.sync="splitvisable">
      <span>猪总重量：{{ rowdata.weight }} kg</span>
      <el-button type="primary" style="padding: 7px;float:right;" @click="addpart">+</el-button>
      <el-table v-loading="splitloading" :data="rowdata.cut_list" max-height="400" :summary-method="getSummaries" show-summary>
        <el-table-column label="重量" align="center" prop="weight">
          <template slot-scope="scope">
            <el-input v-model="scope.row.weight" type="number" placeholder="需要分割的重量" />
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.part_name" placeholder="需要分割部位的名称" />
          </template>
        </el-table-column>
        <el-table-column label=" " width="50">
          <template slot-scope="scope">
            <el-button type="danger" style="padding: 8px;float:right;" @click="subpart(scope.row)">-</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:center; margin-top:20px;">
        <el-button type="danger" @click="clearcut">清空</el-button>
        <el-button type="primary" @click="submitcut">提交</el-button>
        <el-button type="info" @click="cancelcut">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑猪肉" :visible.sync="porkvisable" :rules="porkRules">
      <el-form ref="porkEdit" :model="rowdata">
        <el-form-item label="重量" prop="weight">
          <el-input v-model="rowdata.weight" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="rowdata.part_name" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.native.prevent="onEditSubmit">提交</el-button>
          <el-button @click="onEditCancel">返回</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="购买猪肉" :visible.sync="buyporkvisable" width="80%">
      <el-row style="margin-bottom:10px;">
        <el-input placeholder="猪肉ID" style="margin-left:5px;float:left;width:100px;" />
        <el-input placeholder="部位名称" style="margin-left:5px;float:left;width:150px;" />
        <el-input placeholder="重量" style="margin-left:5px;float:left;width:100px;" />
        <el-input placeholder="加工厂名称" style="margin-left:5px;float:left;width:150px;" />
        <el-button type="primary" icon="el-icon-search" style="margin-left:5px;float:left;width:100px;">搜索</el-button>
      </el-row>
      <el-table v-loading="splitloading" :data="rowdata.list" max-height="400">
        <el-table-column label="猪肉ID" align="center" prop="weight">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column label="加工厂" align="center" prop="weight">
          <template slot-scope="scope">
            {{ scope.row.enterprise.name }}
          </template>
        </el-table-column>
        <el-table-column label="重量" align="center" prop="weight">
          <template slot-scope="scope">
            {{ scope.row.weight }}
          </template>
        </el-table-column>
        <el-table-column label="部位名称" align="center" prop="weight">
          <template slot-scope="scope">
            {{ scope.row.part_name }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" width="150">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="buyPork(scope.row)">购买</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="text-align:center;">
        <el-pagination
          :current-page.sync="rowdata.currentPage"
          :page-size="rowdata.pagesize"
          :page-sizes="[10, 15, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="rowdata.totalcount"
          @current-change="handleCurrentChangeBuy"
          @size-change="handleSizeChangeBuy"
        />
      </div>
    </el-dialog>
    <div class="block" style="margin:10px;">
      <span style="margin-right:5px;">选中 {{ multipleSelection.length }} 项 批量操作</span>
      <el-button :loading="buttonloading" type="danger" @click="deleteRow(multipleSelection)">删除</el-button>
    </div>
    <div class="block" style="text-align:center;">
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pagesize"
        :page-sizes="[10, 15, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalcount"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script>
import { buyPorkList, cutlistPig, cutPork, deletePork, listPork, updatePork } from '@/api/pork'
import { mapGetters } from 'vuex'
import moment from 'moment'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      buttonloading: false,
      splitloading: true,
      currentPage: 1,
      pagesize: 15,
      totalcount: 0,
      splitvisable: false,
      editvisable: false,
      porkvisable: false,
      buyporkvisable: false,
      list: null,
      rowdata: {
        currentPage: 1,
        pagesize: 15,
        totalcount: 0,
        id: 0,
        weight: 0,
        part_name: '',
        cut_date: '',
        list: []
      },
      porkRules: {
        weight: [{ required: true, trigger: 'blur', validator: (rule, value, callback) => {
          if (value.isNaN() === false) {
            callback(new Error('请输入数字'))
          } else if ((Number)(value) <= 0) {
            callback(new Error('请输入有效的重量'))
          } else {
            callback()
          }
        } }],
        name: [{ required: true, trigger: 'blur', validator: (rule, value, callback) => {
          if ((String)(value) === '') {
            callback(new Error('请输入名称'))
          } else {
            callback()
          }
        } }]
      },
      listLoading: true,
      multipleSelection: []
    }
  },
  computed: {
    ...mapGetters([
      'enter_id'
    ])
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    fetchData() {
      this.listLoading = true
      listPork({ current: this.currentPage, size: 15, eid: this.$store.getters.enter_id }).then(response => {
        this.list = response.obj.records
        this.list.forEach((x) => { x.cut_date = moment(x.cut_date).format('YYYY-MM-DD HH:mm:ss') })
        this.listLoading = false
        this.totalcount = response.obj.total
      }).catch(() => { this.listLoading = false })
    },
    editRow(row) {
      this.porkvisable = true
      this.rowdata = row
    },
    addpart() {
      this.rowdata.cut_list.push({ id: 0, weight: undefined, part_name: '' })
    },
    subpart(row) {
      this.$confirm('此操作将删除此条信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePork({ deletearray: [row.id] }).then(() => {
          for (let i = 0; i < this.rowdata.cut_list.length; i++) {
            console.log(row)
            if (this.rowdata.cut_list[i].weight === row.weight && this.rowdata.cut_list[i].part_name === row.part_name) {
              this.rowdata.cut_list.splice(i, 1)
              break
            }
          }
          this.$message('删除成功')
        })
      })
    },
    clearcut() {
      this.$confirm('此操作将清空分块信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePork({ deletearray: this.rowdata.cut_list.map((x) => x.id) }).then(() => {
          this.rowdata.cut_list.splice(0, this.rowdata.cut_list.length)
        })
      })
    },
    submitcut() {
      let total = 0
      for (let i = 0; i < this.rowdata.cut_list.length; i++) {
        total += Number(this.rowdata.cut_list[i].weight)
      }
      if (total > this.rowdata.weight) {
        this.$confirm('分割后的总质量大于目标总质量，是否继续提交？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.addcut()
        }).catch(() => {
          return
        })
      } else {
        this.addcut()
      }
    },
    addcut() {
      this.splitloading = true
      const arr = { array: [], eid: this.$store.getters.enter_id }
      for (let i = 0; i < this.rowdata.cut_list.length; i++) {
        arr.array.push({ id: this.rowdata.cut_list[i].id, enter_id: this.$store.getters.enter_id, part_name: this.rowdata.cut_list[i].part_name, weight: this.rowdata.cut_list[i].weight, cut_date: new Date(), parent: this.rowdata.id, buy: 0 })
      }
      cutPork(arr).then(() => {
        this.$message('添加成功')
        this.splitloading = false
      }).catch(() => { this.splitloading = false })
    },
    cancelcut() {
      this.splitvisable = false
    },
    showsplit(row) {
      this.splitvisable = true
      this.splitloading = true
      this.rowdata = row
      console.log(row)
      cutlistPig({ porkid: row.id, eid: this.$store.getters.enter_id }).then(response => {
        this.rowdata.cut_list = response.obj
        this.splitloading = false
      }).catch(() => { this.splitloading = false })
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = data.length + ' 项'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = sums[index].toFixed(3)
          sums[index] += ' kg'
        } else {
          sums[index] = ' '
        }
      })
      return sums
    },
    newRow() {
      this.buyporkvisable = true
      buyPorkList({ current: this.rowdata.currentPage, size: this.rowdata.pagesize, eid: this.$store.getters.enter_id }).then((response) => {
        this.rowdata.list = response.obj.records
        this.splitloading = false
        this.rowdata.currentPage = 1
        this.rowdata.totalcount = response.obj.total
      }).catch(() => {})
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.handleCurrentChange()
    },
    handleCurrentChange(val) {
      this.list = null
      this.listLoading = true
      listPork({ current: this.currentPage, size: this.pagesize, eid: this.$store.getters.enter_id }).then(response => {
        this.list = response.obj.records
        this.list.forEach((x) => { x.cut_date = moment(x.cut_date).format('YYYY-MM-DD HH:mm:ss') })
        this.listLoading = false
      }).catch(() => { this.listLoading = false })
    },
    handleSizeChangeBuy(val) {
      this.rowdata.pagesize = val
      this.handleCurrentChangeBuy()
    },
    handleCurrentChangeBuy(val) {
      this.rowdata.list = null
      this.splitloading = true
      buyPorkList({ current: this.rowdata.currentPage, size: this.rowdata.pagesize, eid: this.$store.getters.enter_id }).then(response => {
        this.rowdata.list = response.obj.records
        this.rowdata.list.forEach((x) => { x.cut_date = moment(x.cut_date).format('YYYY-MM-DD HH:mm:ss') })
        this.splitloading = false
      }).catch(() => { this.splitloading = false })
    },
    deleteRow(row) {
      if (!(row instanceof Array)) {
        row = [row]
      }
      if (row.length === 0) {
        this.$message({
          type: 'info',
          message: '请至少选中一项'
        })
        return
      }
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.buttonloading = true
        deletePork({ deletearray: row.map(x => x.id) }).then((response) => {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          for (let i = 0; i < this.list.length; i++) {
            for (let j = 0; j < row.length; j++) {
              if (this.list[i].id === row[j].id) {
                this.list.splice(i, 1)
                i--
                row.splice(j, 1)
                j--
                break
              }
            }
          }
          this.buttonloading = false
        })
      }).catch((reason) => {
        console.log(reason)
        this.buttonloading = false
      })
    },
    onEditSubmit() {
      this.$refs.porkEdit.validate(valid => {
        if (valid) {
          this.porkloading = true
          updatePork(this.rowdata).then(() => {
            this.porkvisable = false
            this.$message.success('更新成功')
          })
        }
      })
      this.porkvisable = false
    },
    onEditCancel() {
      this.porkvisable = false
    },
    buyPork(row) {
      this.$confirm('确认要购买此块猪肉吗？', '购买确认', 'info').then(() => {
        row.enter_id = this.$store.getters.enter_id
        row.buy = 1
        updatePork(row).then(() => {
          this.$message.success('购买成功')
          this.splitloading = true
          buyPorkList({ current: this.rowdata.currentPage, size: this.rowdata.pagesize, eid: this.$store.getters.enter_id }).then((response) => {
            this.rowdata.list = response.obj.records
            this.splitloading = false
            this.rowdata.currentPage = 1
            this.rowdata.totalcount = response.obj.total
          }).catch(() => {})
          this.fetchData()
        })
      })
    }
  }
}
</script>
